package users

import (
	"context"
	"errors"
	"product/common/datetime"
	"product/common/validator"
	"strconv"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryUsersLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryUsersLogic query users
func NewQueryUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryUsersLogic {
	return &QueryUsersLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryUsersLogic) QueryUsers(req *types.QueryUserReq) (resp []types.UsersInfo, err error) {
	condition := validQueryUser(req)
	if req.Size == 0 {
		req.Size = 10
	}
	users, err := l.svcCtx.UsersModel.FindPageListByPage(l.ctx, int64(req.Current), int64(req.Size), condition, []string{"ID"})
	if err != nil {
		return nil, errors.New("查询用户失败: " + err.Error())
	}
	for _, user := range users {
		resp = append(resp, types.UsersInfo{
			CreatedAt: datetime.NewUnix(user.CreatedAt).ToFormatByTp(datetime.YearMouthDayHourMinute),
			Email:     user.Email,
			FullName:  user.FullName.String,
			ID:        user.ID,
			Mobile:    user.Mobile,
			Status:    int(user.Status),
			TenantID:  strconv.FormatInt(user.TenantID.Int64, 10),
			UpdatedAt: datetime.NewUnix(user.UpdatedAt.Int64).ToFormatByTp(datetime.YearMouthDayHourMinute),
			UserName:  user.UserName,
		})
	}
	return resp, nil
}

// 验证用户查询条件
func validQueryUser(req *types.QueryUserReq) map[string]interface{} {
	conditions := make(map[string]interface{})
	if !validator.IsEmptyString(req.UserName) {
		conditions["UserName"] = req.UserName
	}
	if !validator.IsEmptyString(req.FullName) {
		conditions["FullName"] = req.FullName
	}
	if !validator.IsEmptyString(req.Mobile) {
		conditions["Mobile"] = req.Mobile
	}
	if !validator.IsEmptyString(req.Email) {
		conditions["Email"] = req.Email
	}
	logx.Infof("conditions: %+v", conditions)
	return conditions
}
